package com.qd.p2p.web.action;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.Iterator;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.qdlc.p2p.common.enums.EnumUploadImgType;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.io.FileUtils;
import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;

import com.alibaba.fastjson.JSONArray;
import com.eitop.platform.tools.encrypt.MD5;
import com.qdlc.p2p.biz.util.FileTypeUtil;
import com.qdlc.p2p.biz.util.OrderNoUtil;
import com.qdlc.p2p.biz.util.PropertiesUtil;
import com.qdlc.p2p.biz.web.action.BaseAction;

/**
 * 静态服务器action
 * 提供图片上传/协议书上传功能接口
 * 所有的图片上传路径中都必须有Nid 参数
 *
 */

public class StaticAction extends BaseAction{
	private Logger logger = Logger.getLogger(StaticAction.class);
	//上传文件
	private File upload;
	private String prefix;
	private String mfileName;
	//上传文件名
	private String uploadFileName;
	//路径拼接符 "/"
	private String sep = File.separator;
	//根据nid的值读取配置文件中的保存路径
	private String nid;
	//方法回调路径
	private String weburl;

	/**
	 * 读取头像方法
	 * 
	 * @throws IOException
	 */
	public String readImg() throws IOException {
		//读取文件相对路径
		String path = request.getParameter("path");
		String contextPath = ServletActionContext.getServletContext().getRealPath("/");
		if(path==""||path==null) return "";
		path = getHandlePath(path);
		String url = contextPath+path;
		File file = new File(url);
		//如果图片不存在 返回Null
		if(!file.exists()){
			return null;
		}
		response.setHeader("Pragma", "No-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setDateHeader("Expires", 0);
		OutputStream output = response.getOutputStream();// 得到输出流
		if (url.toLowerCase().endsWith(".jpg")) {
			// 表明生成的响应是图片
			response.setContentType("image/jpeg");
		} else if (url.toLowerCase().endsWith(".gif")) {
			response.setContentType("image/gif");
		}
		InputStream imageIn = new FileInputStream(file);
		BufferedInputStream bis = new BufferedInputStream(imageIn);// 输入缓冲流
		BufferedOutputStream bos = new BufferedOutputStream(output);// 输出缓冲流
		byte data[] = new byte[4096];// 缓冲字节数
		int size = 0;
		size = bis.read(data);
		while (size != -1) {
			bos.write(data, 0, size);
			size = bis.read(data);
		}
		bis.close();
		bos.flush();// 清空输出缓冲流
		bos.close();
		output.flush();
		output.close();
		return null;
	}
	
	 /**
	  * httpClient请求  保存图片的公用方法
	  * @return
	  */
	 public String httpClientSave(){
		PrintWriter out = null;
		logger.info("nid:"+nid);
		try {
			out = response.getWriter();
		} catch (IOException e1) {
			e1.printStackTrace();
		}
		
		if (!FileTypeUtil.checkFileType(upload)) {
			out.print("error");
			out.flush();
		    out.close();
			return null;
		 }
		
		if(nid==null||nid=="")return null;
		//定义保存的文件名
		String fileName = getMfileName()+"."+prefix;
		//获取save的相对路径
		 String filePath = null;
		 //获取save的相对路径
		 if(!nid.equals(EnumUploadImgType.AUDITION.getValue())) {
			 filePath = getFilePath(nid) + getFolder();
		 }
		 else {
			 filePath = getFilePath(nid);
		 }
		//获取save的绝对路径
		String savePath = getSavePath(filePath);
		//试图创建这个file 如果没有该目录则创建
		File files = new File(savePath);
		if (!files.getParentFile().exists()) {
			try {
				files.getParentFile().mkdirs();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		//创建要生成的文件
		File file=new File(savePath+"/"+fileName);
		try {
			//把上传文件copy到要生成的文件里
			FileUtils.copyFile(upload, file);
		} catch (IOException e) {
			logger.error("上传失败："+e);
			e.printStackTrace();
		}
		//把保存的相对路径返回到客户端
		out.print(JSONArray.toJSON(filePath+"/"+fileName));
		out.flush();
		out.close();
		return null;
	 } 
	 
	 
	 public String index(){
		 return "success";
	 }
	 
	 /**
	  * 使用uploadify方式 请求的保存方法
	  * 图片限制
	  * @return
	  */
	 public String uploadifySave()  {
	    logger.info("uploadify上传..");
		PrintWriter out = null;
		try {
			out = response.getWriter();
		} catch (IOException e) {
			e.printStackTrace();
		}
		if (!FileTypeUtil.checkFileType(upload)) {
			out.print("error");
			out.flush();
		    out.close();
			return null;
		 }
		 //
		 String filePath = getFilePath(nid)+getFolder();
		 String savePath = getSavePath(filePath);
		 //取文件后缀名
		 String prefix = getFileExt(uploadFileName);/*uploadFileName.substring(uploadFileName.lastIndexOf(".")+1);*/
		 
		 String fileName=OrderNoUtil.getSerialNumber()+"."+prefix;
		 File files = new File(savePath);
		 if (!files.getParentFile().exists()) {
			try {
				files.getParentFile().mkdirs();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		 
		File file=new File(savePath+"/"+fileName);
		try {
			FileUtils.copyFile(upload, file);
		} catch (IOException e) {
			logger.error("上传失败："+e);
			e.printStackTrace();
		}
		 out.print(JSONArray.toJSON(filePath+"/"+fileName));
		 out.flush();
		 out.close();
		 return null;
	}
	/**
	 * 头像上传 
	 * @return
	 */
	@SuppressWarnings("resource")
	public String avatar() {
		String pic = request.getParameter("png1");
		if(pic==null||pic=="")return null;
		String filePath = getFilePath("avatar");
		String savePath = getSavePath(filePath);
		String fileName = OrderNoUtil.getSerialNumber() + ".jpg";
		File file = new File(savePath  + fileName);
		if (!file.getParentFile().exists()) {
			try {
				file.getParentFile().mkdirs();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		FileOutputStream fout = null;
		try {
			fout = new FileOutputStream(file);
			fout.write(Base64.decodeBase64(pic));
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		//获取请求方的域名
		String requestUrl = request.getHeader("REFERER");
		if (requestUrl == null){
			return null;
		}
		Pattern p = Pattern.compile("(http://|ftp://|https://|www){0,1}[^\u4e00-\u9fa5\\s]*?\\.(com|net|cn|me|tw|fr)");
		Matcher m = p.matcher(requestUrl);
		while(m.find()){
			requestUrl = m.group(0);
		}
		logger.info("URL来源："+requestUrl);
		weburl =  requestUrl + PropertiesUtil.getMessage("avatarUrl");
		weburl=weburl.replaceAll("/plugins/uploadportrait/face.swf","");
		//传递到平台的Url进行简单处理
		
		String url = weburl + "?avaPic=" + pathHandle(nid,fileName);
		try {
			URLEncoder.encode(url, "UTF-8");
			response.sendRedirect(url);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}	
		
		return null;
	}
	/**
	 * 删除图片（主要用户平台资料上传的删除）
	 * @return
	 */
	public String deleteImg(){
		//图片地址 如: http://localhost:8084/data/img/userinfo/20150506/1505060420614194.jpg
		String url = request.getParameter("imgUrl");
		logger.info("删除URL："+url);
		//请求的host：指图片服务器的域名
		String imgUrl = request.getHeader("Host");
		//截取图片地址中的 域名部分
		String newUrl[] = url.split(imgUrl);
		String contextPath = ServletActionContext.getServletContext().getRealPath("/");
		if(newUrl.length>0){
			url = contextPath + newUrl[newUrl.length-1];
		}
		File file = new File(url);
		if(file.exists()){
			file.delete();
		}
		return null;
	}
	
	/**
	 * MD5加密字符串方法
	 * @param fileName
	 * @return
	 */
	public String getMd5Str(String fileName){
		MD5 md5 = new MD5();
		return md5.getMD5ofStr(fileName);
	}
	
	/**
	 * 取默认图片路径
	 * @return
	 */
	public String getDefaultPath(){
		String contextPath = ServletActionContext.getServletContext().getRealPath("/");
		String url = contextPath + sep +"data"+ sep + "upload" + sep + "images" + sep + "noavatar_default"  + ".gif";;
		return url;
	}
	
	/**
	 * 获取完整的保存路径
	 * @param path
	 * @return
	 */
	public String getSavePath(String path){
		String contextPath = ServletActionContext.getServletContext().getRealPath("/");
		return contextPath+path;
	}
	
	/**
	 * 传递给平台放路径处理
	 * @param nid  类型
	 * @param fileName 图片名字
	 * @return
	 */
	public String pathHandle(String nid,String fileName){
		//需要返回的url格式/xxx/xxx-xx
		String url = "/"+nid+"/"+fileName.replace(".", "-");
		return url;
	}
	/**
	 * 根据平台传递的Path 反处理得到真实的图片路径
	 * @param path
	 * @return
	 */
	public String getHandlePath(String path){
		//path为固定模式 /xxx/xxx-xx xxx表示图片类型的Nid,xxx-xx标识图片的名字+后缀
		String split[] = path.split("/");
		String result = "";
		if(split.length>=2){
			result = getFilePath(split[1]);
			if(!split[1].equals("default")){
				result += split[2].replace("-", ".");
			}
		}
		return result;
	}
	
	/**
	 * 读取配置文件中的存储路径
	 * @param nid
	 * @return
	 */
	public String getFilePath(String nid){
		if(nid==null||nid=="")return "";
		return PropertiesUtil.getMessage(nid);
	}
	
	/**
	 * 取随机字符串
	 * @param length 字符串长度
	 * @return
	 */
	public  String getRandomString(int length) { 
	    String base = "abcdefghijklmnopqrstuvwxyz0123456789#%!~*";   
	    Random random = new Random();   
	    StringBuffer sb = new StringBuffer(); 
	    int number = 0;
	    for (int i = 0; i < length; i++) {   
	         number = random.nextInt(base.length());   
	        sb.append(base.charAt(number));   
	    }   
	    return sb.toString();   
	 }  
	
	/**
	 * 年月日目录
	 * @return
	 */
	public String getFolder(){
		SimpleDateFormat formater = new SimpleDateFormat("yyyyMMdd");
		return formater.format(new Date());
	}
	
	/**
	 * 校验是否是图片
	 * @param fileName
	 * @return
	 */
	@SuppressWarnings({ "rawtypes", "unused" })
	private boolean checkFileType(String fileName) {
		String[] fileType = {"gif" , "png" , "jpg" , "jpeg" , "pdf"};
		Iterator type = Arrays.asList(fileType).iterator();
		while (type.hasNext()) {
			String ext = (String) type.next();
			if (fileName.toLowerCase().endsWith(ext)) {
				return true;
			}
		}
		return false;
	}
	
	/**
	 * 去文件名后缀
	 * @param fileName
	 * @return
	 */
	private String getFileExt(String fileName) {
		return fileName.substring(fileName.lastIndexOf(".")+1);
	}
	
	//-------------------------get/set------------------------------------------
	
	public String getPrefix() {
		return prefix;
	}

	public void setPrefix(String prefix) {
		this.prefix = prefix;
	}

	public String getUploadFileName() {
		return uploadFileName;
	}

	public void setUploadFileName(String uploadFileName) {
		this.uploadFileName = uploadFileName;
	}

	public String getWeburl() {
		return weburl;
	}

	public void setWeburl(String weburl) {
		this.weburl = weburl;
	}

	public File getUpload() {
		return upload;
	}

	public void setUpload(File upload) {
		this.upload = upload;
	}

	public String getSep() {
		return sep;
	}

	public void setSep(String sep) {
		this.sep = sep;
	}

	public String getNid() {
		return nid;
	}
	
	public void setNid(String nid) {
		this.nid = nid;
	}

	public String getMfileName() {
		return mfileName;
	}

	public void setMfileName(String mfileName) {
		this.mfileName = mfileName;
	}

}
